<template>
  <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    width="50%"
    @open="open"
    @close="close"
  >
    <el-tree
      ref="tree"
      :data="menus"
      show-checkbox
      node-key="id"
      :props="props"
      default-expand-all
      :default-checked-keys="checkedKeys"
      :expand-on-click-node="false">
      <div class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
      </div>
    </el-tree>
    <div class="operation">
      <el-button type="primary" size="small" plain @click="handleCancel">取消</el-button>
      <el-button type="primary" size="small" @click="handleConfirm">授权</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator'

  @Component
  export default class Dialog extends Vue {
    dialogVisible: boolean = false
    menus = []
    checkedKeys = []
    props = {
      children: 'menuDtos',
      label: 'name'
    }
    @Prop({
      default: ''
    }) currentID: string

    showDialog () {
      this.dialogVisible = true
    }

    hiddenDialog () {
      this.dialogVisible = false
    }

    async getCurrentRoles () {
      let res: AjaxResponse = await this.$axios.get(`b/boms/rolemenu/role/${this.currentID}/menus`)
      let rootMenuId = this.menus.map(v => v.id)
      if (res.responseCode === 200) {
        this.checkedKeys = res.data.filter(v => {
          return rootMenuId.indexOf(v) === -1
        })
      }
    }

    async getAllRoles () {
      let res: AjaxResponse = await this.$axios('b/boms/menu/menus')
      if (res.responseCode === 200) {
        this.menus = res.data
        this.getCurrentRoles()
      }
    }

    async handleConfirm () {
      let menus = this.$refs.tree.getCheckedNodes().map(val => val.id)
      this.menus.forEach(menu => {
        menu.menuDtos.forEach(dto => {
          if (menus.indexOf(dto.id) !== -1) {
            menus.push(menu.id)
          }
        })
      })
      menus =  Array.from(new Set(menus).values())
      menus = menus.map(v => ({menuId: v}))
      let res: AjaxResponse = await this.$axios.post('b/boms/rolemenu/add', {
        roleId: this.currentID,
        menus
      })
      this.$utils.tips(res)
      this.hiddenDialog()
    }

    handleCancel () {
      this.hiddenDialog()
    }

    open () {
      this.getAllRoles()
    }

    close () {
      this.checkedKeys = null
      this.menus = null
    }
  }
</script>

<style lang="less" scoped>
  .operation {
    display: flex;
    flex-direction: row-reverse;
    > * {
      margin-right: 30px;
    }
  }

</style>
